<?php

namespace W3\Element;

use W3\Element;

/**
 * Table 帮手类
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */

class Table extends Element
{
    public $table, $thead, $tbody, $tfoot, $caption;

    /**
     * 实例化
     *
     * @access public
     * @param mixed $config 配置列表
     */
    public function __construct($class = NULL)
    {
		$this->close(false)
		    ->tag('div')
			->addClass('table-responsive');
		
		/** 设置表单标签 */
		$this->table = Element::make('table')->addClass($class ?? 'table');
		$this->thead = Element::make();
		$this->tbody = Element::make();
		$this->tfoot = Element::make();
		$this->caption = Element::make();

		$this->table
			->set($this->caption, NULL, 'caption')
		    ->set($this->thead, NULL, 'thead')
		    ->set($this->tbody, NULL, 'tbody')
			->set($this->tfoot, NULL, 'tfoot');

		$this->set($this->table);
    }
	
    public function head($data, $class = NULL)
    {
		!is_array($data) && $data = [$data];
		
		$tr = Element::make('tr');
		$tmpStr = '';
		$th = Element::make('th', '%s')->render();
        foreach ($data as $var) 
		{
			if(is_array($var)) { 
			    list($_element, $_class) = $var;
				$tmpStr .= Element::make('th', $_element)->addClass($_class)->render();
			}else{
				$tmpStr .= sprintf($th, $var);
			}
	    }
		
		$class && $this->thead->addClass($class);
		$tmpStr && $this->thead->tag('thead')->set($tr->set($tmpStr), NULL, 'tr');
		return $this;
    }
	
    /**
     * 向列表中添加行
     * @param  mixed  data
     * @return object ListRow
     */
    public function body($data, $class = NULL)
    {
		!is_array($data) && $data = [$data];
		
		$tr = Element::make('tr');
		$tmpStr = '';
		$td = Element::make('td', '%s')->render();
        foreach ($data as $var) 
		{
			if(is_array($var)) { 
			    list($_element, $_class) = $var;
				$tmpStr .= Element::make('td', $_element)->addClass($_class)->render();
			}else{
				$tmpStr .= sprintf($td, $var);
			}
	    }
		
		$class && $this->tbody->addClass($class);
		$tmpStr && $this->tbody->tag('tbody')->set($tr->set($tmpStr), NULL, 'tr');
		return $this;
    }
	
    public function foot($data, $class = NULL)
    {
		!is_array($data) && $data = [$data];
		
		$tr = Element::make('tr');
		$tmpStr = '';
		$td = Element::make('td', '%s')->render();
        foreach ($data as $var) 
		{
			if(is_array($var)) { 
			    list($_element, $_class) = $var;
				$tmpStr .= Element::make('td', $_element)->addClass($_class)->render();
			}else{
				$tmpStr .= sprintf($td, $var);
			}
	    }
		
		$class && $this->tfoot->addClass($class);
		$tmpStr && $this->tfoot->tag('tfoot')->set($tr->set($tmpStr), NULL, 'tr');
		return $this;
    }
}

